package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Clazz> findByList(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> clazzPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<Clazz>()
                .like(!StringUtils.isEmpty(name), Clazz::getName, name)
                .between(!ObjectUtils.isEmpty(begin) && !ObjectUtils.isEmpty(end), Clazz::getCreateTime, begin, end);
        this.page(clazzPage, queryWrapper);
        clazzPage.getRecords().forEach(
                clazz -> {
                    if (clazz.getMasterId() != null) {
                        Emp emp = empMapper.selectById(clazz.getMasterId());
                        if (emp != null) {
                            clazz.setMasterName(emp.getName());
                        }
                    }
                    if (clazz.getBeginDate().isAfter(LocalDate.now())) {
                        clazz.setStatus("未开班");
                    } else if (clazz.getEndDate().isBefore(LocalDate.now())) {
                        clazz.setStatus("已结课");
                    } else {
                        clazz.setStatus("已开班");
                    }
                });
        return new PageResult<>(clazzPage.getTotal(), clazzPage.getRecords());
    }

    @Override
    public void saveClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        this.save(clazz);
    }
}
